# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function

from ..ops import Ref, Mean
from ..base import OpsFeature

from .high import High
from .low import Low
from .volume import Volume

class EMV(OpsFeature):
    """Technical Indicator - EMV

    - VOLUME = MA(VOL, N) / VOL
    - MID = (HIGH + LOW - REF(HIGH + LOW, 1)) / (HIGH + LOW) * 100
    - TEMP = MID * VOLUME * (HIGH-LOW) 
    - EMV = MA(TEMP / MA(HIGH - LOW, N), N)
    """
    def __init__(self, N=14):
        self.N = N

    def __str__(self):
        name = type(self).__name__.lower()
        if self.N != 14:
            name += '_'+str(self.N)
        return name

    def _load_internal(self, instrument, start_time, end_time, freq):
        vol = Mean(Volume(), self.N) / Volume()
        hpl = High() + Low()
        hml = High() - Low()
        mid = (hpl - Ref(hpl, 1)) / hpl * 100
        tmp = mid * vol * hml
        emv = Mean(tmp / Mean(hml, self.N), self.N)
        return emv.load(instrument, start_time, end_time, freq)
